// components/activity-registration/index.js
Component({
  properties: {
    // 是否显示弹窗
    show: {
      type: Boolean,
      value: false
    },
    // 活动信息
    activity: {
      type: Object,
      value: {}
    }
  },

  data: {
    // 参与者信息列表
    participants: [
      {
        name: '',
        phone: ''
      }
    ],
    // 备注信息
    notes: '',
    // 总金额（基于新参与者）
    totalAmount: 0,
    // 实际新参与者数量
    newParticipantsCount: 0,
    // 已存在的参与者
    existingParticipants: [],
    // 是否正在提交
    isSubmitting: false,
    // 是否正在检查参与者状态
    isCheckingParticipants: false,
    // 参与者检查结果
    participantCheckResult: null
  },

  observers: {
    'show': function(show) {
      if (show) {
        // 弹窗显示时，重置检查状态
        console.log('报名弹窗显示，当前参与者:', this.data.participants);
        console.log('当前活动:', this.data.activity);
        
        // 重置检查状态，但不自动检查
        this.setData({
          participantCheckResult: null,
          isCheckingParticipants: false
        });
      }
    }
  },

  methods: {
    // 关闭弹窗
    onClose() {
      this.setData({
        show: false,
        participants: [{
          name: '',
          phone: ''
        }],
        notes: '',
        totalAmount: 0,
        newParticipantsCount: 0,
        existingParticipants: [],
        participantCheckResult: null,
        isCheckingParticipants: false,
        isSubmitting: false
      });
      this.triggerEvent('close');
    },

    // 添加参与者
    onAddParticipant() {
      const participants = [...this.data.participants];
      participants.push({
        name: '',
        phone: ''
      });
      this.setData({
        participants: participants
      });
    },

    // 删除参与者
    onRemoveParticipant(e) {
      const index = e.currentTarget.dataset.index;
      if (this.data.participants.length <= 1) {
        wx.showToast({
          title: '至少需要一名参与者',
          icon: 'none'
        });
        return;
      }
      
      const participants = [...this.data.participants];
      participants.splice(index, 1);
      this.setData({
        participants: participants
      });
    },

    // 参与者姓名输入
    onNameInput(e) {
      const index = e.currentTarget.dataset.index;
      const value = e.detail.value;
      const participants = [...this.data.participants];
      participants[index].name = value;
      this.setData({
        participants: participants
      });
    },

    // 参与者电话输入
    onPhoneInput(e) {
      const index = e.currentTarget.dataset.index;
      const value = e.detail.value;
      const participants = [...this.data.participants];
      participants[index].phone = value;
      this.setData({
        participants: participants
      });
    },

    // 备注输入
    onNotesInput(e) {
      this.setData({
        notes: e.detail.value
      });
    },

    // 验证表单
    validateForm() {
      const { participants } = this.data;
      
      for (let i = 0; i < participants.length; i++) {
        const participant = participants[i];
        if (!participant.name.trim()) {
          wx.showToast({
            title: `请填写第${i + 1}位参与者姓名`,
            icon: 'none'
          });
          return false;
        }
        
        if (!participant.phone.trim()) {
          wx.showToast({
            title: `请填写第${i + 1}位参与者电话`,
            icon: 'none'
          });
          return false;
        }
        
        // 验证手机号格式
        const phoneRegex = /^1[3-9]\d{9}$/;
        if (!phoneRegex.test(participant.phone)) {
          wx.showToast({
            title: `第${i + 1}位参与者电话格式不正确`,
            icon: 'none'
          });
          return false;
        }
      }
      
      return true;
    },

    // 提交报名
    async onSubmit() {
      const { participants, activity } = this.data;
      
      if (!this.validateForm()) {
        return;
      }

      // 检查是否有参与者
      const validParticipants = participants.filter(p => p.name.trim() && p.phone.trim());
      if (validParticipants.length === 0) {
        wx.showToast({
          title: '请至少添加一位参与者',
          icon: 'none'
        });
        return;
      }

      console.log('=== 开始报名流程 ===');
      console.log('表单参与者:', validParticipants);

      // 强制重新检查参与者状态，确保数据准确
      this.setData({ isSubmitting: true });
      
      try {
        await this.checkParticipantsStatus();
        
        const finalCheckResult = this.data.participantCheckResult;
        if (!finalCheckResult) {
          console.error('无法获取检查结果');
          wx.showToast({ title: '检查失败，请重试', icon: 'none' });
          return;
        }

        const newParticipants = finalCheckResult.newParticipants;
        const existingParticipants = finalCheckResult.existingParticipants;

        console.log('检查结果:', {
          newParticipants: newParticipants,
          existingParticipants: existingParticipants
        });

        if (newParticipants.length === 0) {
          // 所有参与者都已报名
          const existingNames = existingParticipants.map(p => p.name).join('、');
          wx.showModal({
            title: '无法报名',
            content: `以下参与者已报名该活动：
${existingNames}

请更换其他参与者信息后重试。`,
            showCancel: false,
            confirmText: '知道了'
          });
          return;
        }

        if (existingParticipants.length > 0) {
          // 部分已报名的情况
          const existingNames = existingParticipants.map(p => p.name).join('、');
          const newNames = newParticipants.map(p => p.name).join('、');
          
          wx.showModal({
            title: '提示',
            content: `以下参与者已报名，将被跳过：
${existingNames}

将为以下新参与者报名：
${newNames}

是否继续？`,
            showCancel: true,
            confirmText: '继续',
            cancelText: '取消',
            success: (res) => {
              if (res.confirm) {
                this.proceedWithRegistration(newParticipants, existingParticipants);
              }
            }
          });
        } else {
          // 全部是新参与者，直接提交
          this.proceedWithRegistration(newParticipants, existingParticipants);
        }
      } catch (error) {
        console.error('检查参与者状态失败:', error);
        wx.showToast({ title: '检查失败，请重试', icon: 'none' });
      } finally {
        this.setData({ isSubmitting: false });
      }
    },

    // 检查参与者状态
    async checkParticipantsStatus() {
      const { participants, activity } = this.data;
      if (!activity || !(activity.id || activity._id)) {
        console.log('活动信息不完整，无法检查参与者状态');
        return;
      }

      // 过滤掉空参与者
      const validParticipants = participants.filter(p => p.name.trim() && p.phone.trim());
      if (validParticipants.length === 0) {
        this.setData({
          totalAmount: 0,
          newParticipantsCount: 0,
          existingParticipants: [],
          participantCheckResult: {
            newParticipants: [],
            existingParticipants: [],
            canProceed: false
          }
        });
        return;
      }

      console.log('开始检查参与者状态，数据:', {
        activityId: activity.id || activity._id,
        participants: validParticipants
      });

      this.setData({
        isCheckingParticipants: true
      });

      try {
        // 调用云函数检查参与者状态
        const result = await wx.cloud.callFunction({
          name: 'checkExistingParticipants',
          data: {
            activityId: activity.id || activity._id,
            participants: validParticipants
          }
        });

        console.log('云函数返回结果:', result);

        if (result.result && result.result.success) {
          const { newParticipants, existingParticipants } = result.result;
          const newCount = newParticipants.length;
          const totalAmount = newCount * (activity.price || 0);

          this.setData({
            totalAmount: totalAmount,
            newParticipantsCount: newCount,
            existingParticipants: existingParticipants,
            participantCheckResult: {
              newParticipants,
              existingParticipants,
              canProceed: newCount > 0
            }
          });
          
          console.log(`检查完成: ${newCount}位新参与者, ${existingParticipants.length}位已存在`);
        } else {
          console.error('云函数检查失败:', result.result?.message || '未知错误');
          // 如果检查失败，允许用户继续报名
          const totalAmount = validParticipants.length * (activity.price || 0);
          this.setData({
            totalAmount: totalAmount,
            newParticipantsCount: validParticipants.length,
            existingParticipants: [],
            participantCheckResult: {
              newParticipants: validParticipants,
              existingParticipants: [],
              canProceed: true
            }
          });
        }
      } catch (error) {
        console.error('检查参与者状态失败:', error);
        // 网络错误时允许用户继续报名
        const totalAmount = validParticipants.length * (activity.price || 0);
        this.setData({
          totalAmount: totalAmount,
          newParticipantsCount: validParticipants.length,
          existingParticipants: [],
          participantCheckResult: {
            newParticipants: validParticipants,
            existingParticipants: [],
            canProceed: true
          }
        });
        
        console.log('网络错误，允许用户继续报名');
      } finally {
        this.setData({
          isCheckingParticipants: false
        });
      }
    },

    // 处理报名流程（包含免费和付费活动）
    async proceedWithRegistration(newParticipants, existingParticipants) {
      const { activity } = this.data;
      const totalAmount = newParticipants.length * (activity.price || 0);

      console.log('=== 开始报名流程 ===');
      console.log('活动ID:', activity._id || activity.id);
      console.log('新参与者:', newParticipants);
      console.log('支付金额:', totalAmount);

      if (totalAmount <= 0) {
        // 免费活动，跳过支付流程
        console.log('免费活动，跳过支付流程');
        await this.createFreeRegistration(newParticipants, existingParticipants);
      } else {
        // 付费活动，使用微信支付流程
        await this.createPaidRegistration(newParticipants, existingParticipants);
      }
    },

    // 处理免费活动报名
    async createFreeRegistration(newParticipants, existingParticipants) {
      const { activity } = this.data;

      try {
        // 调用云函数创建免费报名记录
        const result = await wx.cloud.callFunction({
          name: 'submitActivityRegistration',
          data: {
            activityId: activity._id || activity.id,
            participants: newParticipants,
            notes: this.data.notes,
            totalAmount: 0
          }
        });

        console.log('创建免费报名结果:', result);

        if (!result.result || result.result.success === false) {
          wx.showToast({
            title: result.result?.message || '报名失败',
            icon: 'none'
          });
          return;
        }

        const { registrationId } = result.result;

        // 报名成功提示
        wx.showModal({
          title: '报名成功',
          content: `已为${newParticipants.length}位新参与者成功报名免费活动！`,
          showCancel: false,
          confirmText: '确定',
          success: () => {
            this.triggerEvent('success', {
              registrationId: registrationId,
              totalAmount: 0,
              cashbackAmount: 0,
              newParticipantsCount: newParticipants.length,
              skippedParticipantsCount: existingParticipants.length,
              newParticipants: newParticipants,
              skippedParticipants: existingParticipants
            });
            this.onClose();
          }
        });

      } catch (error) {
        console.error('免费报名失败:', error);
        wx.showToast({
          title: '报名失败，请重试',
          icon: 'none'
        });
      } finally {
        this.setData({
          isSubmitting: false
        });
      }
    },

    // 处理付费活动微信支付流程
    async createPaidRegistration(newParticipants, existingParticipants) {
      const { activity } = this.data;
      const totalAmount = newParticipants.length * (activity.price || 0);

      try {
        // 第1步：创建待支付报名记录
        const payResult = await wx.cloud.callFunction({
          name: 'createActivityPayOrder',
          data: {
            activityId: activity._id || activity.id,
            participants: newParticipants,
            notes: this.data.notes
          }
        });

        console.log('创建支付订单结果:', payResult);

        if (!payResult.result || payResult.result.success === false) {
          wx.showToast({
            title: payResult.result?.message || '创建支付订单失败',
            icon: 'none'
          });
          return;
        }

        const result = payResult.result;
        const { registrationId, wechatOrderNo, totalAmount: actualAmount } = result;

        // 第2步：调起微信支付 - 使用云开发返回的payment对象中的支付参数
        const payRes = await new Promise((resolve, reject) => {
          wx.requestPayment({
            timeStamp: result.payment.timeStamp,
            nonceStr: result.payment.nonceStr,
            package: result.payment.package,
            signType: result.payment.signType,
            paySign: result.payment.paySign,
            success: resolve,
            fail: reject
          });
        });

        console.log('微信支付成功:', payRes);

        // 第3步：支付成功后，触发成功事件（后端activityPayNotify会处理后续逻辑）
        wx.showModal({
          title: '支付成功',
          content: `支付成功！已为${newParticipants.length}位新参与者完成报名，返现¥${actualAmount}已到账`,
          showCancel: false,
          confirmText: '确定',
          success: () => {
            this.triggerEvent('success', {
              registrationId: registrationId,
              totalAmount: actualAmount,
              cashbackAmount: actualAmount,
              newParticipantsCount: newParticipants.length,
              skippedParticipantsCount: existingParticipants.length,
              newParticipants: newParticipants,
              skippedParticipants: existingParticipants
            });
            this.onClose();
          }
        });

      } catch (error) {
        console.error('微信支付失败:', error);
        
        if (error.errMsg && error.errMsg.includes('requestPayment:fail')) {
          // 用户取消支付或其他支付失败
          wx.showToast({
            title: '支付已取消',
            icon: 'none'
          });
        } else {
          wx.showToast({
            title: '支付失败，请重试',
            icon: 'none'
          });
        }
      } finally {
        this.setData({
          isSubmitting: false
        });
      }
    },

    // 阻止冒泡
    onStopPropagation() {
      // 阻止事件冒泡，防止点击内容区域关闭弹窗
      return false;
    }
  }
});